package com.xiezc.util;

import com.alibaba.fastjson.JSON;
import com.xiaoleilu.hutool.cache.impl.TimedCache;
import com.xiezc.dto.ExcepEnum;
import com.xiezc.dto.RespData;
import com.xiezc.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created by wb-xzc291800 on 2017/6/22.
 */
@Component
public class TicketInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private TimedCache timedCache;

    /**
     * 请求前调用
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String ticket = httpServletRequest.getHeader("ticket");
        User user = findUserByTicket(ticket);
        if (!Objects.isNull(user)) {
            httpServletRequest.setAttribute("user", user);
            return true;
        }
        httpServletResponse.setCharacterEncoding("utf8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(JSON.toJSON( RespData.fail(ExcepEnum.NotLogin)));
        httpServletResponse.getWriter().flush();
        return false;
    }

    /**
     * 根据ticket获得timedCache中保存的登录 用户的信息
     *
     * @param ticket
     * @return
     */
    private User findUserByTicket(String ticket) {
        User user = (User) timedCache.get(ticket);
        if (StringUtils.isEmpty(user)) {
            timedCache.remove(ticket);
            return null;
        }
        timedCache.put(ticket, user);
        return user;
    }
}
